/**
 * 聊天记录存储模块
 */
import { BaseStorage, DBManager, StorageConfig } from './dbBase';

// 聊天消息类型定义
export interface ChatMessage {
    role: 'user' | 'assistant';
    content: string;
    timestamp: number;
}

// 聊天记录类型定义
export interface ChatRecord {
    chatId: string;
    messages: ChatMessage[];
    model: string;
    title: string;
    desc: string;
}

// 聊天记录存储配置
export const CHAT_STORAGE_CONFIG: StorageConfig = {
    storageName: 'chatHistory'
};

/**
 * 初始化聊天记录存储
 */
export const initChatStorage = (db: IDBDatabase): void => {
    if (!db.objectStoreNames.contains(CHAT_STORAGE_CONFIG.storageName)) {
        const store = db.createObjectStore(CHAT_STORAGE_CONFIG.storageName, { keyPath: 'chatId' });
        store.createIndex('chatId', 'chatId', { unique: true });
        console.log(`创建存储对象: ${CHAT_STORAGE_CONFIG.storageName}`);
    }
};

/**
 * 聊天记录存储类
 * 提供聊天记录的CRUD操作
 */
export class ChatStorage extends BaseStorage<ChatRecord> {
    protected storageConfig: StorageConfig = CHAT_STORAGE_CONFIG;

    constructor(dbManager: DBManager) {
        super(dbManager);
    }

    /**
     * 添加聊天记录
     */
    async add(chat: ChatRecord): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.add(chat);
                    request.onsuccess = () => {
                        console.log('聊天记录添加成功:', chat.chatId);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('聊天记录添加失败:', error);
            return false;
        }
    }

    /**
     * 更新聊天记录
     */
    async update(chat: ChatRecord): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.put(chat);
                    request.onsuccess = () => {
                        console.log('聊天记录更新成功:', chat.chatId);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('聊天记录更新失败:', error);
            return false;
        }
    }

    /**
     * 删除聊天记录
     */
    async delete(chatId: string): Promise<boolean> {
        try {
            const storeName = this.storageConfig.storageName;
            await (this.dbManager as any).executeTransaction(
                storeName,
                'readwrite',
                (store: IDBObjectStore) => {
                    const request = store.delete(chatId);
                    request.onsuccess = () => {
                        console.log('聊天记录删除成功:', chatId);
                    };
                    return request;
                }
            );
            return true;
        } catch (error) {
            console.error('聊天记录删除失败:', error);
            return false;
        }
    }

    /**
     * 获取单条聊天记录
     */
    async get(chatId: string): Promise<ChatRecord | null> {
        try {
            const storeName = this.storageConfig.storageName;
            const result = await (this.dbManager as any).executeTransaction(
                storeName,
                'readonly',
                (store: IDBObjectStore) => store.get(chatId)
            );
            return result || null;
        } catch (error) {
            console.error('获取聊天记录失败:', error);
            return null;
        }
    }

    /**
     * 获取所有聊天记录
     */
    async getAll(): Promise<ChatRecord[]> {
        try {
            const storeName = this.storageConfig.storageName;
            const result = await (this.dbManager as any).executeTransaction(
                storeName,
                'readonly',
                (store: IDBObjectStore) => store.getAll()
            );
            return result || [];
        } catch (error) {
            console.error('获取所有聊天记录失败:', error);
            return [];
        }
    }

    /**
     * 向聊天添加新消息
     */
    async addMessage(chatId: string, message: ChatMessage): Promise<boolean> {
        const chat = await this.get(chatId);

        if (!chat) {
            console.error('聊天记录不存在:', chatId);
            return false;
        }

        chat.messages.push(message);
        return this.update(chat);
    }
} 